<template>
    <el-container class="app-container" v-loading="loading">
        <el-header class="list-title" style="height: auto;">
              <span>
                机柜：{{params.rackNumber}}(共{{count}}台，{{run}}台开机状态，{{stop}}台关机)
              </span>
                    <span>
                所属:{{params.rackDept}}
              </span>
            <!--<div>
              <el-button type="success" size="mini" @click="powerOn">批量开机</el-button>
              <el-button type="info"  size="mini" @click="shutDown">批量关机</el-button>
            </div>-->
        </el-header>
        <el-main style="height: 500px;">
            <DynamicTable
                    :columns="tableColumns"
                    :list="tableData" :current-page="currentPage"
                    ref="singleTable"
                    @selection-change="handleSelectionChange"
            >
                <template slot="end">
                    <el-table-column label="操作" align="center" :min-width="200" :fixed="fixed">
                        <template slot-scope="scope">
                            <el-button @click="handleOn(scope.row)" type="text" size="small" v-if="scope.row.machineType==='服务器'">开机</el-button>
                            <el-button @click="handleDown(scope.row)" type="text" size="small" v-if="scope.row.machineType==='服务器'">关机</el-button>
                            <el-button @click="handleDelete(scope.row)" type="text" size="small">下架</el-button>
                        </template>
                    </el-table-column>
                </template>
            </DynamicTable>
        </el-main>

        <el-dialog
                :title="centerDialogTitle"
                :visible.sync="centerDialogVisible"
                :close-on-click-modal="false"
                :append-to-body="true"
                v-loading="dialogloading"
                width="30%"
                center>


            <el-form :model="deviceForm" :rules="userRules" ref="deviceForm" label-width="100px" size="medium"
                     :key="centerDialogVisible">
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="用户名" prop="osUser">
                            <el-input v-model="deviceForm.osUser"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20">
                        <el-form-item label="密码" prop="osPass">
                            <el-input
                                    type="password"
                                    auto-complete="off"
                                    v-model.trim="deviceForm.osPass"
                                    placeholder="请输入新密码"
                                    onpaste="return false"
                                    onselectstart="return false"
                                    v-filterSpecialChar
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="保存账号密码">
                            <el-switch v-model="deviceForm.isSave"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogDown">确 定</el-button>
            </span>
        </el-dialog>

    </el-container>
</template>
<script>
import CuPopover from '@/common/CuPopover';
import DynamicTable from '@/common/DynamicTable';

export default {
  name: 'Config',
  components: {
    CuPopover, DynamicTable
  },
  data() {
    return {
      count: 0,
      run: 0,
      stop: 0,
      fixed: false,
      dialogloading: false,
      shutDownForm: null,
      centerDialogVisible: false,
      centerDialogTitle: '',
      deviceForm: {
        osUser: '',
        osPass: '',
        isSave: false
      },
      formData: {},
      userRules: {
        osUser: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        osPass: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
      loading: false,
      currentPage: 0,
      tableData: [],
      tableColumns: [
        {
          field: 'assetNumber',
          title: '资产编号',
          width: '80px',
        },
        {
          field: 'ip',
          title: '设备IP',
          width: '140px',
        },
        {
          field: 'mac',
          title: 'MAC地址',
          width: '140px',
        },
        {
          field: 'machineType',
          title: '设备类型',
          width: '100px',
        },
        {
          field: 'responsible',
          title: '负责人',
          width: '100px',
        },
        {
          field: 'usage',
          title: '设备用途',
        },
        {
          field: 'runTime',
          title: '运行时间',
          width: '100px',
          renderer: (v) => {
            let str = '';
            switch (v.runTime) {
            case 9:
              str = '9H';
              break;
            case 12:
              str = '12H';
              break;
            case 24:
              str = '永不关机';
              break;
            case -1:
              str = String('0'.repeat(2) + v.startOnTime).slice(-2) + ':00' + '-' + String('0'.repeat(2) + v.shutdownTime).slice(-2) + ':00';
              break;
            }

            return str
          }
        },
        {
          field: 'state',
          title: '状态',
          width: '80px',
          renderer: (v) => {
            return v.state === 0 ? '<span style=\'color:#67C23A;\'>开机</span>' : '<span style=\'color:red;\'>关机</span>'
          }
        },
      ],
      multipleSelection: [],
    }
  },
  switch: {
    centerDialogVisible: {
      handler(val, o) {
        if (!val) this.shutDownForm = {}
      },
      immediate: true,
      deep: true
    },
  },
  props: ['params'],
  methods: {
    getRowKey(row) {
      return row.id;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    powerOn() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning({
          showClose: true,
          message: '至少选择一条数据！',
        });
        return;
      }

      this.$confirm('确定要全部开机？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        this.loading = true;
        let promise = [];
        this.multipleSelection.forEach(d => {
          let id = d;
          let p = new Promise((resolve, reject) => {
            this.$axiosInstance({
              method: 'get',
              url: '/switchMachine',
              params: {
                id
              }
            })
              .then(result => {
                if (result.data.code === 200) {
                  resolve();
                } else {
                  reject();
                }
              })
              .catch(() => {
              });
          });
          promise.push(p);
        });
        Promise.all(promise).then(() => {
          console.log('全部执行完毕');
          this.loadData();
        }).catch(() => {
          this.loading = false;
        })
      })
    },
    dialogDown() {
      this.$refs['deviceForm'].validate((v) => {
        if (!v) return
        this.dialogloading = true;
        this.offMachine(this.shutDownForm, () => {
          this.dialogloading = false;
        });
      });
    },
    shutDown() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning({
          showClose: true,
          message: '至少选择一条数据！',
        });
        return;
      }
      this.$confirm('确定要全部关机？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        this.loading = true;
        let promise = [];
        this.multipleSelection.forEach(d => {
          let id = d;
          let p = new Promise((resolve, reject) => {
            this.$axiosInstance({
              method: 'get',
              url: '/switchMachine',
              params: {
                id
              }
            })
              .then(result => {
                if (result.data.code === 200) {
                  resolve();
                } else {
                  reject();
                }
              })
              .catch(() => {
              });
          });
          promise.push(p);
        });
        Promise.all(promise).then(() => {
          console.log('全部执行完毕');
          this.loadData();
        }).catch(() => {
          this.loading = false;
        })
      })
    },

    handleOn(row) {
      // this.centerDialogTitle='开机';
      // this.centerDialogVisible=true;
      this.$confirm('确定要开机？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        // this.centerDialogTitle='开机';
        // this.centerDialogVisible=true;
        this.switchMachine(row);
      })
    },
    handleDown(row) {
      this.$confirm('确定要关机？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        if (!row.pwIsExist) {
          this.centerDialogTitle = '关机';
          this.centerDialogVisible = true;
          this.shutDownForm = row;
        } else {
          this.offMachine(row);
        }
      })
    },
    offMachine(row, call) {
      this.loading = true;
      this.$axiosInstance({
        method: 'get',
        url: '/offMachine',
        params: {
          id: row.id,
          ...this.deviceForm
        }
      })
        .then(result => {
          if (result.data.code === 200) {
            this.$message({
              message: result.data.message,
              type: 'success'
            });
            this.loadData();
          } else {
            this.$message({
              message: result.data.message,
              type: 'error'
            });
          }
          this.loadData();
          this.loading = false;
          if (call) call();
        })
        .catch(() => {
          this.loading = false;
          if (call) call();
        });
    },
    switchMachine(row) {
      this.loading = true;
      this.$axiosInstance({
        method: 'get',
        url: '/onMachine',
        params: {
          id: row.id
        }
      })
        .then(result => {
          if (result.data.code === 200) {
            this.$message({
              message: result.data.message,
              type: 'success'
            });
            this.loadData();
          } else {
            this.$message({
              message: result.data.message,
              type: 'error'
            });
          }
          this.loadData();
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    open() {
      this.$nextTick(() => {
        this.loadData();
      })
    },
    // 根据id查询
    loadData() {
      if (this.params) {
        this.loading = true;
        this.$axiosInstance({
          method: 'get',
          url: '/getMachineDetail.json',
          params: {
            rackDept: this.params.rackDept,
            rackNumber: this.params.rackNumber
          }
        })
          .then(result => {
            let { data, code } = result.data;
            if (code === 200) {
              this.tableData = data;
              this.count = data.length;
              let r = 0;
              let s = 0;
              for (let i = 0; i < data.length; i++) {
                if (data[i].state === 0) {
                  r++;
                } else {
                  s++;
                }
              }
              this.run = r;
              this.stop = s;
            } else {
              this.$message({
                message: result.data.message,
                type: 'error'
              });
            }
            this.loading = false
          })
          .catch(() => {
            this.loading = false
          });

      }

    },
    handleDelete(item) {
      this.$confirm('确定要下架吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        this.$axiosInstance({
          method: 'get',
          url: '/downMachine',
          params: {
            id: item.id
          }
        })
          .then(result => {
            if (result.data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1000,
              });
              this.loadData();
            } else {
              this.$message({
                message: '操作失败',
                type: 'error'
              });
            }
            this.loadData();
          })
          .catch(() => {
          });
      })

    },
    // 取消
    onBack() {
      this.$confirm(
        (this.dialogType == 'add' ? '新建' : '修改') +
                '操作尚未保存，是否确认退出？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        this.$emit('close')
      })
    },
    mounted() {
      this.loadData()
      this.$nextTick(() => {
        let pw = this.$refs['singleTable'].$el.getBoundingClientRect().width;
        let tw = this.$refs['singleTable'].$el.querySelector('.el-table__body').getBoundingClientRect().width;

        if (tw > pw) {
          this.fixed = 'right';
        }
      })
    },
  },
}
</script>
<style lang="less" scoped>
    .el-container .list-title {
        height: auto;
        padding: 0px 5px 25px;
        font-size: 20px;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        span{
            padding-right: 25px;
        }
    }
</style>
